// pages/labor/applicants/applicants.js
const app = getApp()

Page({
  data: {
    laborId: null,
    jobTitle: '',
    applicantsList: [],
    loading: true,
    currentPage: 1,
    pageSize: 10,
    total: 0,
    totalPages: 0,
    hasMore: true
  },

  onLoad(options) {
    const { laborId } = options
    if (laborId) {
      this.setData({ laborId })
      this.loadApplicants()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }
  },

  async loadApplicants(isLoadMore = false) {
    if (!isLoadMore) {
      wx.showLoading({ title: '加载中...' })
    }
    
    try {
      const result = await app.utils.request({
        url: `/labor/applications/${this.data.laborId}/page`,
        method: 'GET',
        data: {
          page: this.data.currentPage,
          size: this.data.pageSize
        }
      })
      
      if (result.code === 200) {
        const pageData = result.data
        const applicantsList = pageData.records || []
        
        // 格式化申请时间
        applicantsList.forEach(applicant => {
          if (applicant.applicationTime) {
            applicant.applicationTime = this.formatTime(applicant.applicationTime)
          }
        })
        
        // 如果是加载更多，追加到现有列表
        const newList = isLoadMore ? 
          [...this.data.applicantsList, ...applicantsList] : 
          applicantsList
        
        this.setData({
          applicantsList: newList,
          jobTitle: applicantsList.length > 0 ? applicantsList[0].jobTitle : this.data.jobTitle,
          total: pageData.total || 0,
          totalPages: pageData.pages || 0,
          hasMore: this.data.currentPage < (pageData.pages || 0),
          loading: false
        })
      } else {
        throw new Error(result.message || '获取申请者列表失败')
      }
    } catch (error) {
      console.error('获取申请者列表失败:', error)
      this.setData({ loading: false })
      if (!isLoadMore) {
        app.utils.showError(error.message || '获取申请者列表失败')
      }
    }
    
    if (!isLoadMore) {
      wx.hideLoading()
    }
  },

  // 加载更多
  loadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
      this.loadApplicants(true)
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      currentPage: 1,
      applicantsList: [],
      hasMore: true
    })
    this.loadApplicants().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 触底加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  copyContact(e) {
    const { type, value } = e.currentTarget.dataset
    
    wx.setClipboardData({
      data: value,
      success: () => {
        wx.showToast({
          title: `${type === 'phone' ? '手机号' : type === 'qq' ? 'QQ号' : '微信号'}已复制`,
          icon: 'success',
          duration: 2000
        })
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'error'
        })
      }
    })
  },

  reviewApplication(e) {
    const { id, status } = e.currentTarget.dataset
    let statusText = ''
    let content = ''
    
    switch (status) {
      case 'accepted':
        statusText = '接受'
        content = '确定要接受这个申请吗？'
        break
      case 'rejected':
        statusText = '拒绝'
        content = '确定要拒绝这个申请吗？'
        break
      case 'completed':
        statusText = '标记完成'
        content = '确定要将此申请标记为完成吗？'
        break
      default:
        statusText = '操作'
        content = '确定要执行此操作吗？'
    }
    
    wx.showModal({
      title: `确认${statusText}`,
      content: content,
      success: async (res) => {
        if (res.confirm) {
          await this.submitReview(id, status)
        }
      }
    })
  },

  async submitReview(applicationId, status) {
    wx.showLoading({ title: '处理中...' })
    
    try {
      let reviewNote = ''
      let successMessage = ''
      
      switch (status) {
        case 'accepted':
          reviewNote = '申请已通过'
          successMessage = '已接受申请'
          break
        case 'rejected':
          reviewNote = '申请未通过'
          successMessage = '已拒绝申请'
          break
        case 'completed':
          reviewNote = '申请已完成'
          successMessage = '已标记完成'
          break
        default:
          reviewNote = '状态已更新'
          successMessage = '操作成功'
      }
      
      const result = await app.utils.request({
        url: '/labor/review',
        method: 'POST',
        data: {
          applicationId: parseInt(applicationId),
          status: status,
          reviewNote: reviewNote
        }
      })
      
      wx.hideLoading()
      
      if (result.code === 200) {
        wx.showToast({
          title: successMessage,
          icon: 'success'
        })
        
        // 重新加载申请者列表
        this.loadApplicants()
      } else {
        throw new Error(result.message || '操作失败')
      }
    } catch (error) {
      wx.hideLoading()
      console.error('审核申请失败:', error)
      app.utils.showError(error.message || '操作失败')
    }
  },

  formatTime(timeStr) {
    if (!timeStr) return ''
    
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前'
    }
    
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前'
    }
    
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前'
    }
    
    // 超过7天，显示具体日期
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  }
})
